package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.AppWarehouseCreateBo;
import org.dromara.system.domain.vo.AppWarehouseListVo;
import org.dromara.system.domain.vo.AppWarehouseSumVo;
import org.dromara.system.domain.vo.AppWarehouseTotalVo;
import org.dromara.system.mapper.*;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.AppWarehouseBo;
import org.dromara.system.domain.vo.AppWarehouseVo;
import org.dromara.system.service.IAppWarehouseService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 仓库Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppWarehouseServiceImpl implements IAppWarehouseService {

    private final AppWarehouseMapper baseMapper;
    private final SysTenantMapper sysTenantMapper;
    private final AppProcurementPlanMapper appProcurementPlanMapper;
    private final AppOrderMapper appOrderMapper;
    private final AppWarehouseMapper appWarehouseMapper;
    private final AppWarehouseRecordMapper appWarehouseRecordMapper;

    /**
     * 查询仓库
     *
     * @param id 主键
     * @return 仓库
     */
    @Override
    public AppWarehouseVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询仓库列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 仓库分页列表
     */
    @Override
    public TableDataInfo<AppWarehouseVo> queryPageList(AppWarehouseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppWarehouse> lqw = buildQueryWrapper(bo);
        Page<AppWarehouseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的仓库列表
     *
     * @param bo 查询条件
     * @return 仓库列表
     */
    @Override
    public List<AppWarehouseVo> queryList(AppWarehouseBo bo) {
        LambdaQueryWrapper<AppWarehouse> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppWarehouse> buildQueryWrapper(AppWarehouseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppWarehouse> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppWarehouse::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), AppWarehouse::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsType()), AppWarehouse::getGoodsType, bo.getGoodsType());
        if (bo.getType()!=null && bo.getType()==1){
            lqw.groupBy(AppWarehouse::getStoreId);
        }
        lqw.eq(bo.getStock() != null, AppWarehouse::getStock, bo.getStock());
        return lqw;
    }

    /**
     * 新增仓库
     *
     * @param bo 仓库
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppWarehouseBo bo) {
        AppWarehouse add = MapstructUtils.convert(bo, AppWarehouse.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改仓库
     *
     * @param bo 仓库
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppWarehouseBo bo) {
        AppWarehouse update = MapstructUtils.convert(bo, AppWarehouse.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppWarehouse entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除仓库信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public TableDataInfo<AppWarehouseVo> listByCompanyId(AppWarehouseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppWarehouse> lqw = buildQueryWrapper(bo);
        lqw.eq(AppWarehouse::getTenantId,bo.getTenantId());
        Page<AppWarehouseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public R<List<AppWarehouseTotalVo>> queryByIdAndSearch(String query) {

        //查询的公司id
        String tenantId = null;

        //查询的采购计划编号
        String planCode = null;

        List<AppWarehouseTotalVo> res = new ArrayList<>();


        //查询是否有匹配的公司
        if (StringUtils.isNotBlank(query)){
            LambdaQueryWrapper<SysTenant> sysTenantLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysTenantLambdaQueryWrapper.like(SysTenant::getCompanyName,query);
            List<SysTenant> sysTenants = sysTenantMapper.selectList(sysTenantLambdaQueryWrapper);
            if (CollUtil.isNotEmpty(sysTenants)){
                SysTenant first = CollUtil.getFirst(sysTenants);
                tenantId = first.getTenantId();
            }
            if (tenantId==null){
                LambdaQueryWrapper<AppProcurementPlan> appProcurementPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appProcurementPlanLambdaQueryWrapper.like(AppProcurementPlan::getPlanCode,query);
                List<AppProcurementPlan> appProcurementPlans = appProcurementPlanMapper.selectList(appProcurementPlanLambdaQueryWrapper);
                if (CollUtil.isNotEmpty(appProcurementPlans)){
                    AppProcurementPlan first = CollUtil.getFirst(appProcurementPlans);
                    planCode = first.getPlanCode();
                }
            }
        }
        //查询是否有匹配的采购编号
        LambdaQueryWrapper<AppProcurementPlan> ap = new LambdaQueryWrapper<>();
        ap.eq(planCode!=null,AppProcurementPlan::getPlanCode,planCode);
        ap.eq(tenantId!=null,AppProcurementPlan::getTenantId,tenantId);
        List<AppProcurementPlan> appProcurementPlans = appProcurementPlanMapper.selectList(ap);
        if (CollUtil.isNotEmpty(appProcurementPlans)){
            for (AppProcurementPlan appProcurementPlan : appProcurementPlans) {
                AppWarehouseTotalVo appWarehouseTotalVo = new AppWarehouseTotalVo();
                appWarehouseTotalVo.setName(appProcurementPlan.getCompanyName());
                appWarehouseTotalVo.setPlanCode(appProcurementPlan.getPlanCode());
                //仓库名称 根据采购编号查询订单里的仓库名称
                LambdaQueryWrapper<AppOrder> appOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                appOrderLambdaQueryWrapper.eq(AppOrder::getPlanId,appProcurementPlan.getId());
                AppOrder appOrder = appOrderMapper.selectOne(appOrderLambdaQueryWrapper);
                if (appOrder!=null){
                    List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(new LambdaQueryWrapper<AppWarehouse>().eq(AppWarehouse::getStoreId, appOrder.getWarehouseId()));
                    if (CollUtil.isNotEmpty(appWarehouses)){
                        AppWarehouse appWarehouse = CollUtil.getFirst(appWarehouses);
                        appWarehouseTotalVo.setStoreName(appWarehouse.getName());
                    }
                }
                res.add(appWarehouseTotalVo);
            }

        }

        return R.ok(res);
    }

    @Override
    public R<List<AppWarehouseSumVo>> lookWareHouse(String query) {
        List<AppWarehouseSumVo> res = new ArrayList<>();
        LambdaQueryWrapper<AppWarehouse> appWarehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseLambdaQueryWrapper.like(StringUtils.isNotBlank(query),AppWarehouse::getName,query);
        List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(appWarehouseLambdaQueryWrapper);
        if (CollUtil.isNotEmpty(appWarehouses)){
            Map<Long, List<AppWarehouse>> collect = appWarehouses.stream().collect(Collectors.groupingBy(AppWarehouse::getStoreId));
            collect.forEach((k,v)->{
                AppWarehouseSumVo appWarehouseSumVo = new AppWarehouseSumVo();
                appWarehouseSumVo.setName(CollUtil.getFirst(v).getName());
                appWarehouseSumVo.setId(k);
                appWarehouseSumVo.setAppWarehouse(v);
                long sum = v.stream().mapToLong(AppWarehouse::getStock).sum();
                appWarehouseSumVo.setTotalWeight(sum);
                res.add(appWarehouseSumVo);
            });
        }
        return R.ok(res);
    }

    @Override
    public R<Void> createNew(AppWarehouseCreateBo appWarehouseCreateBo) {
        AppWarehouseRecord appWarehouseRecord = new AppWarehouseRecord();
        appWarehouseRecord.setType(1);
        appWarehouseRecord.setStorageType(1L);
        //新建出库
        return null;
    }

    @Override
    public R<List<AppWarehouseSumVo>> listStoreByCompanyId(AppWarehouseBo bo) {
        List<AppWarehouseSumVo> res = new ArrayList<>();
        LambdaQueryWrapper<AppWarehouse> appWarehouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appWarehouseLambdaQueryWrapper.eq(AppWarehouse::getTenantId,bo.getTenantId());
        List<AppWarehouse> appWarehouses = appWarehouseMapper.selectList(appWarehouseLambdaQueryWrapper);
        if (CollUtil.isNotEmpty(appWarehouses)){
            Map<Long, List<AppWarehouse>> collect = appWarehouses.stream().collect(Collectors.groupingBy(AppWarehouse::getStoreId));
            collect.forEach((k,v)->{
                AppWarehouseSumVo appWarehouseSumVo = new AppWarehouseSumVo();
                appWarehouseSumVo.setName(CollUtil.getFirst(v).getName());
                appWarehouseSumVo.setId(k);
                appWarehouseSumVo.setAppWarehouse(v);
                long sum = v.stream().mapToLong(AppWarehouse::getStock).sum();
                appWarehouseSumVo.setTotalWeight(sum);
                res.add(appWarehouseSumVo);
            });
        }
        return R.ok(res);
    }
}
